/*
 * @LastEditTime: 2023-02-28 11:30:54
 */
import { PlayHistory } from "../Models/PlayHistory.Schema";
import { createPlayHistoryDTO, updatePlayHistorysDTO } from "../DTO/PlayHistory.dto";
import { isExistsforId, isExistsforUsername } from "../hook";

export class PlayHistoryController {
  constructor(private readonly playHistoryModel: typeof PlayHistory) { }

  /**
   * 创建记录
   * @param dto 数据传输对象
   * @returns 返回创建对象
   */
  async createItem(dto: createPlayHistoryDTO) {
    await this.playHistoryModel.deleteMany({ username: dto.username, musicId: dto.musicId })
    console.log(dto)
    try {
      return {
        code: 200,
        message: "记录成功",
        data: await this.playHistoryModel.create(dto),
      };

    } catch (error) {
      return await error;
    }
  }

  /**
   * 按ID更新记录
   * @param id 要更新的ID
   * @param dto  要更新的内容
   * @returns 更新对象
   */
  async updateById(id: string, dto: updatePlayHistorysDTO) {
    try {
      if (!!await isExistsforId(id, this.playHistoryModel)) {
        return {
          code: 400,
          message: '不存在查询的ID',
        }
      } else {
        return {
          code: 200,
          message: "更新成功",
          data: await this.playHistoryModel.updateOne({ _id: id }, dto),
        };
        console.log(1)
      }
    } catch (error) {
      return await error;
    }
  }

  /**
   * 按记录名称查找记录
   * @param title 要查找的记录名称
   * @returns 查询对象
   */
  async findByUsername(name: string) {
    try {
      if (await isExistsforUsername(name, this.playHistoryModel)) {
        return {
          code: 200,
          message: '暂无数据',
        }
      } else {
        return {
          code: 200,
          message: "查询成功",
          data: await this.playHistoryModel.find({ username: name }).sort({ createdAt: -1 }),
        };
      }
    } catch (error) {
      return await error;
    }
  }
}